var Resource = require('/utils/remotedata/Resource');
var RestClient = require('/utils/remotedata/RestClient');

/**
 *
 *
 * @params: {
 * 	requests : [
 * 		{name:'',resource:'',params:null},
 * 		...
 * 	],
 *  callbackExito:null,
 *  callbackError:null,
 * }
 * @params
 */
function MultiRequest(params){
	
	var self = this;
	
	this.requests = [];
	this.allResponse = {};
	this.callbackExito = undefined;
    this.callbackError = undefined;
	
	/* El request debe tener la siguiente estructura:
	 * @request: tiene la siguiente estructura {name:'',resource:'',params:''}
	 * @name: es para identificar el request, la respuesta del request estara asociada a este nombre.
	 * @resource: es un recurso del tipo '/utils/remotedata/Resource'
	 * @params: parametros del request
	 * Ejemplo: {name:'UserInfo', resource:Request.user.info, params:{userId:1}}
	 */
	this.addRequest = function(request){
		if(typeof(request.name) === 'undefined' || request.name == null) {
			throw "El parametro name es requerido.";
		}
		if(typeof(request.resource) === 'undefined' || request.resource == null) {
			throw "El parametro 'resource' es requerido.";
		}
		if(typeof(request.params) === 'undefined' || request.params == null) {
			throw "El parametro 'params' es requerido.";
		}
		self.requests.push(request);
	};
	
	/**
	 * 
	 */
	this.send = function() {
		setTimeout(_send, 0);
	};
	
	function _send() {
		
		var errorInACall = false;
		var countResult = 0;
		
		function processLastResult(){
			if(errorInACall){
				self.callbackError();
			} else {
				self.callbackExito(self.allResponse);
			}
		};
	
		function ExitResultForCall(request){
		    var _request = request;
		    return function(response){
		    	self.allResponse[request.name] = response;
		    	countResult = countResult + 1;
				if (countResult === self.requests.length) {
					processLastResult();
				}
			};
		};
	
		function manageErrorResult(error) {
			errorInACall = true;
			countResult = countResult + 1;
			if (countResult === self.requests.length) {
				processLastResult();
			}
		}

		for(var i = 0 ; i < self.requests.length ; i++) {
			var request = self.requests[i];
			var manageExitResult = new ExitResultForCall(request);
			RestClient.invocar(request.resource,request.params,manageExitResult, manageErrorResult);
		}
	
	};
};

module.exports = MultiRequest;
